﻿using Framework.AspNetCore.User;
using Framework.Core.Consts;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Users;
using Framework.Core.Extensions;
using my.abp.Domain.Shared.Entities;
using my.abp.Domain.IManagers.User;
using my.abp.Domain.IManagers.Menu;
using my.abp.Domain.Managers.User;

namespace my.abp.Domain.Authorization
{
	/// <summary>
	/// 默认数据权限判断
	/// </summary>
	public class DefaultPermissionHandler : IPermissionHandler, ITransientDependency
	{
		private Framework.AspNetCore.User.CurrentUser _currentUser { get; set; }
		private IHttpContextAccessor _httpContextAccessor;
		private readonly ISysUserManager _sysUserManager;
		private readonly ISysMenuManager _sysMenuManager;

		public DefaultPermissionHandler(ISysUserManager sysUserManager, 
			Framework.AspNetCore.User.CurrentUser currentUser, 
			IHttpContextAccessor httpContextAccessor,
			ISysMenuManager sysMenuManager)
		{
			_currentUser = currentUser;
			_httpContextAccessor = httpContextAccessor;
			_sysUserManager = sysUserManager;
			_sysMenuManager = sysMenuManager;
		}

		/// <summary>
		/// 判断当前用户是否有对应权限
		/// </summary>
		/// <param name="permission"></param>
		/// <returns></returns>
		public async Task<bool> IsPass()
		{
			if (_currentUser.Account == null) return true;

			if (_currentUser.SuperAdmin) return true;

			SysUser user = await _sysUserManager.GetAsync(_currentUser.Account);

			// 路由名称
			var routeName = _httpContextAccessor.HttpContext.Request.Path.StartsWithSegments("/api")
				? _httpContextAccessor.HttpContext.Request.Path.Value[5..].Replace("/", ":")
				: _httpContextAccessor.HttpContext.Request.Path.Value[1..].Replace("/", ":");

			// 获取用户拥有按钮权限集合
			var ownBtnPermList = await _sysMenuManager.GetOwnBtnPermList();
			// 获取系统所有按钮权限集合
			var allBtnPermList = await _sysMenuManager.GetAllBtnPermList();

			// 已拥有该按钮权限或者所有按钮集合里面不存在
			var exist1 = ownBtnPermList.Exists(u => routeName.Equals(u, System.StringComparison.CurrentCultureIgnoreCase));
			var exist2 = allBtnPermList.TrueForAll(u => !routeName.Equals(u, System.StringComparison.CurrentCultureIgnoreCase));
			return (exist1 || exist2);
		}
	}
}
